package com.tticar.invmanager.controller;

import com.tticar.invmanager.common.shiro.LoginUser;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by yandou on 2018/6/26.
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private HttpSession session;

    @PostMapping("login")
    @ResponseBody
    public MyResponseBody plogin(String username, String password) {
        MyResponseBody responseBody = MyResponseBody.success();
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            LoginUser loginUser = (LoginUser) subject.getPrincipal();
            MySecurityUtils.setCurrentUser(loginUser);

            session.setAttribute("_tenant_id_", loginUser.getTenantId());
            session.setMaxInactiveInterval(-1);
            sysUserService.logLogin(loginUser);
            return responseBody;
        } catch (AuthenticationException e) {
            responseBody.setCode(MyResponseBody.CODE_FAILURED);
            responseBody.setMessage(e.getMessage());
        } catch (Exception e) {
            responseBody.setCode(MyResponseBody.CODE_FAILURED);
            responseBody.setMessage("登录失败,联系管理员。");
        }
        return responseBody;
    }

    @GetMapping("logout")
    @ResponseBody
    public MyResponseBody logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession(false).stop();
        subject.logout();
        subject.getSession().removeAttribute("current_user");
        return MyResponseBody.success();
    }

    @GetMapping("login")
    public String login() {
        return "login/login";
    }

    @GetMapping("login2")
    public String login2() {
        return "login";
    }

}
